package cfdt.ldl.dspchannel.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cpcn.dsp.institution.api.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cpcn.dsp.institution.api.security.EncryptAndDecrypt;
import cpcn.dsp.institution.api.system.DSPInstitutionEnvironment;
import cpcn.dsp.institution.api.tx.corpquery.Tx1161Request;
import cpcn.dsp.institution.api.tx.corpquery.Tx1161Response;
import cfdt.ldl.common.utils.http.HttpClientUtil;
import cfdt.common.vo.BaseResponse;
import cfdt.ldl.dspchannel.api.request.DcQueryRiskInformationRequest;
import cfdt.ldl.dspchannel.api.response.DcQueryRiskInformationResponse;
import cfdt.ldl.dspchannel.service.BaseInterface;
import cfdt.ldl.dspchannel.system.SystemEnvironment;
import cfdt.ldl.tools.exception.CodeException;
import cfdt.tools.util.StringUtils;
import cpcn.dsp.institution.api.util.Base64;

@Service(value = "queryRiskInformationService")
public class QueryRiskInformationServiceImpl implements BaseInterface {
    private static final Logger LOGGER = LoggerFactory.getLogger("queryRiskInformationService");

    @Autowired
    private SystemEnvironment systemEnvironment;

    @Override
    public BaseResponse process(Object request) throws CodeException {
        BaseResponse response = new BaseResponse();
        DcQueryRiskInformationResponse dcQueryRiskInformationResponse = new DcQueryRiskInformationResponse();
        DcQueryRiskInformationRequest dcQueryRiskInformationRequest = (DcQueryRiskInformationRequest) request;
        try {
            Map<String, String> systemparamMap = systemEnvironment
                    .getProperties(dcQueryRiskInformationRequest.getInstitutionID());
            DSPInstitutionEnvironment.initialize(systemparamMap.get("privateKey"), systemparamMap.get("keyPassword"),
                    systemparamMap.get("publicKey"), systemparamMap.get("encryptType"));
            dcQueryRiskInformationRequest.setInstitutionID(systemparamMap.get("patnCode"));
            Map<String, String> paramMap = params(dcQueryRiskInformationRequest);
            // 生成请求参数
            String requestString = "";
            requestString = EncryptAndDecrypt.createLinkStringByGet(paramMap);
            String result = HttpClientUtil.doPost(SystemEnvironment.requestUrl, requestString,
                    30000, 30000, "UTF-8", "application/x-www-form-urlencoded");
            String respPlainText = null;
            String[] respMsg = StringUtils.trim(result).split(",");
            if (respMsg.length == 1 && -1 == respMsg[0].indexOf(',')) {
                respPlainText = Base64.decode(respMsg[0], "UTF-8");
                LOGGER.info("响应明文：{}", respPlainText);
                dcQueryRiskInformationResponse.setStatus(30);
                dcQueryRiskInformationResponse.setResponseCode("3911");
                dcQueryRiskInformationResponse.setResponseMessage("司法风险信息查询失败");
            } else if (respMsg.length == 5) {
                String responseMessage = respMsg[0];
                String responseSignature = respMsg[1];
                String responseDgtlEnvlp = respMsg[2];
                String respSignSN = respMsg[3];
                String respEncryptSN = respMsg[4];
                Tx1161Response tx1161Response = new Tx1161Response(responseMessage, responseSignature,
                        responseDgtlEnvlp, respSignSN, respEncryptSN);
                respPlainText = tx1161Response.getResponsePlainText();
                LOGGER.info("响应明文：{}", respPlainText);
                if(StringUtil.isEmpty(respPlainText)) {
                    throw new CodeException("3911", "司法风险信息查询统计响应报文为空");
                }
                JSONObject jsonObject = JSONObject.parseObject(respPlainText);
                String code = jsonObject.getString("Code");
                if(!"2000".equals(code)) {
                    dcQueryRiskInformationResponse.setStatus(30);
                    dcQueryRiskInformationResponse.setResponseCode(code);
                    dcQueryRiskInformationResponse.setResponseMessage(jsonObject.getString("Message"));
                    dcQueryRiskInformationResponse.setChannelSerialNumber(jsonObject.getString("TraceNo"));
                }
                if ("2000".equals(tx1161Response.getCode())) {
                    dcQueryRiskInformationResponse.setChannelSerialNumber(tx1161Response.getTraceNo());
                    dcQueryRiskInformationResponse.setResponseCode(tx1161Response.getResponseCode());
                    dcQueryRiskInformationResponse.setResponseMessage(tx1161Response.getResponseMessage());
                    if (tx1161Response.getExternalJudicialStatisticsList() != null
                            && !tx1161Response.getExternalJudicialStatisticsList().isEmpty()) {
                        List<Map<String, String>> judicialStatisticsList = new ArrayList<Map<String, String>>();
                        for (int i = 0; i < tx1161Response.getExternalJudicialStatisticsList().size() - 1; i++) {
                            Map<String, String> JudicialStatisticMap = new HashMap<String, String>();
                            JudicialStatisticMap.put("DataType",
                                    tx1161Response.getExternalJudicialStatisticsList().get(i).getDataType());
                            JudicialStatisticMap.put("DetailId",
                                    tx1161Response.getExternalJudicialStatisticsList().get(i).getDetailId());
                            JudicialStatisticMap.put("DetailNum",
                                    tx1161Response.getExternalJudicialStatisticsList().get(i).getDetailNum());
                            judicialStatisticsList.add(JudicialStatisticMap);
                        }
                        dcQueryRiskInformationResponse.setJudicialStatisticsList(judicialStatisticsList);
                    }
                    dcQueryRiskInformationResponse.setStatus(20);
                }
            }
        } catch (CodeException e) {
            LOGGER.error(e.getCode(), e.getMessage());
            dcQueryRiskInformationResponse.setResponseCode(e.getCode());
            dcQueryRiskInformationResponse.setResponseMessage(e.getMessage());
            dcQueryRiskInformationResponse.setStatus(10);
        } catch (Exception e) {
            LOGGER.error("司法风险信息查询统计异常", e);
            dcQueryRiskInformationResponse.setResponseCode("3911");
            dcQueryRiskInformationResponse.setResponseMessage("司法风险信息查询统计异常");
            dcQueryRiskInformationResponse.setStatus(10);
        }
        response.setBody(dcQueryRiskInformationResponse);
        return response;
    }

    @Override
    public Map<String, String> params(Object request) throws CodeException {
        DcQueryRiskInformationRequest dcQueryRiskInformationRequest = (DcQueryRiskInformationRequest) request;
        Tx1161Request tx1161Request = new Tx1161Request();
        tx1161Request.setInstitutionID(dcQueryRiskInformationRequest.getInstitutionID());
        tx1161Request.setName(dcQueryRiskInformationRequest.getInstitutionName());
        tx1161Request.setRemark(dcQueryRiskInformationRequest.getRemark());
        tx1161Request.setTxSN(dcQueryRiskInformationRequest.getSerialNumber());
        tx1161Request.setUniformSocialCreditCode(dcQueryRiskInformationRequest.getOrgCode());
        try {
            tx1161Request.process();
        } catch (Exception e) {
            LOGGER.error("司法风险信息查询统计报文处理异常", e);
            throw new CodeException("3911", "司法风险信息查询统计报文处理异");
        }
        String plainText = tx1161Request.getRequestPlainText();
        LOGGER.info("请求明文:{}", plainText);
        String reqMessage = tx1161Request.getRequestMessage();
        String reqSignature = tx1161Request.getRequestSignature();
        String requestDgtlEnvlp = tx1161Request.getRequestDgtlEnvlp();
        String requestSignSN = tx1161Request.getRequestSignSN();
        String requestEncryptSN = tx1161Request.getRequestEncryptSN();
        String institutionID = tx1161Request.getInstitutionID();
        // 生成参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("institutionID", tx1161Request.getInstitutionID());
        paramMap.put("message", reqMessage);
        paramMap.put("signature", reqSignature);
        paramMap.put("dgtlenvlp", requestDgtlEnvlp);
        paramMap.put("signSN", requestSignSN);
        paramMap.put("encryptSN", requestEncryptSN);
        paramMap.put("institutionID", institutionID);
        return paramMap;
    }
}
